import React, { PureComponent, Fragment } from 'react';
import { FormattedMessage, formatMessage } from 'umi/locale';
import {
  Row,
  Col,
  Form,
  Input,
  DatePicker,
  Badge,
  Divider,
  TreeSelect,
  Upload,
  Icon,
  Tooltip
} from 'antd';
import {Select,Button , Table ,Modal,Pagination} from '@/components/CustomAntd'
import { usePlatform } from '@/defaultSettings.js';

const { TreeNode } = TreeSelect;
import { connect } from 'dva';
const { Option } = Select;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const FormItem = Form.Item;
@connect(({ permission_management, loading }) => ({
  permission_management,
  loading: loading.models.permission_management,
}))
@Form.create()
export default class CustomModal extends PureComponent {

  validator(rule,valuse){
    const { form } = this.props;
    const is_left_menu = form.getFieldValue("is_left_menu");
    // const route = form.getFieldValue("route");
    //const pattern = new RegExp("[/]");
    if (is_left_menu && is_left_menu == 2){
      //console.log(valuse && /^[^/]+$/.test(valuse));
      if (valuse && ! (/^[^/]+$/.test(valuse))){
        return true
      } else {
        return false
      }
      return false
    } else if (is_left_menu && is_left_menu == 3){
     return false
    }
  };
  selectMenu(){
    const { form } = this.props;
    form.resetFields("route");
  }
  platformTypeChange =(value)=>{
    const { dispatch } = this.props;

    dispatch({
      type: "permission_management/noRouteTypeChange",
      payload: {
        platform_type:value.join(',') ,
        is_left_menu:'1,4',
      },
    }).then(()=>{
      this.props.form.resetFields('permission_pid');
    })

  }
  renderTreeNodes = treeList => treeList.map((item) => {
    if(item.is_left_menu === '1' || item.is_left_menu === '4' ){
      if (item.permissions) {
        return (
          <TreeNode title={item.permission_name} disabled = {true} key={item.permission_id}  value={item.permission_id}>
            {this.renderTreeNodes(item.permissions)}
          </TreeNode>
        );
      } else {
        return (
          <TreeNode
            title={item.permission_name}
            key={item.permission_id}
            value={item.permission_id}>
          </TreeNode>
        );
      }
    }
    return [];
  })
  render() {
    const{
      visible,
      updateData,
      modalType,
      modalHandleCancel,
      modalHandleOk,
      typesList,
      platformtnameList,
      selectId
    } = this.props;
    const deptsArray = updateData && updateData.platform_type ? updateData.platform_type.split(",") :undefined;
    const { permission_management: { noRouteTreeList },form } = this.props;
    const platformType = deptsArray ? deptsArray.slice(0,-1):undefined
    const { form: { getFieldDecorator, getFieldValue, getFieldsValue, setFieldsValue, resetFields }, loading, } = this.props;
    const platform_type = form.getFieldValue("platform_type");
    //确认
    const onOk = e => {
      e.preventDefault();
      let subFields
      if (modalType === 'edit') {
        subFields = {
          permission_id: updateData.permission_id,
        }
      }

      form.validateFields((err, fieldsValue) => {
        if (err) return;

        if(fieldsValue.platform_type != undefined){
          let list = '';

          for (var i = 0; i < fieldsValue.platform_type.length; i++) {
            list += fieldsValue.platform_type[i] + ',';
          }
          subFields = {
            ...subFields,
            ...fieldsValue,
            modalType: modalType,
            platform_type: list
          };
        }else{
          subFields = {
            ...subFields,
            ...fieldsValue,
            modalType: modalType,

          };
        }
        //console.log(subFields);
        modalHandleOk(subFields, e);

      });
    }

    return (
      <Modal
        title={modalType === 'create' ? '新增功能' :
          modalType === 'edit' ? '修改功能' : ''}
        width={800}
        visible={visible}
        onCancel={modalHandleCancel}
        onOk={onOk}
      >

        <div>
          {/*{
            modalType == 'edit' ?
              <FormItem
                {...formItemLayout}
                label={formatMessage({ id: 'iot.permission.columns.permission_id' })}
                required={true}
              >
                {getFieldDecorator('permission_id', {
                  initialValue: this.props.updateData.permission_id,
                  validateTrigger: ['onChange', 'onBlur'],
                })(
                  <Input disabled="disabled" style={{ width: '445px' }} placeholder="请输入" />
                )}
              </FormItem>
              :
              <FormItem
                {...formItemLayout}
                label={formatMessage({ id: 'iot.permission.columns.permission_id' })}
                required={true}
              >
                {getFieldDecorator('permission_id', {
                  initialValue: modalType == 'edit' ? this.props.updateData.permission_id : undefined,
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    {
                      pattern: /^[^ ]+$/,
                      max: 32,
                      required: true,
                      whitespace: true,
                      message: '请输入32位以内功能id(不能包含空格)',
                    },
                    {
                      pattern: /^[0-9a-zA-Z_\\-]{1,}$/,
                      message: '禁止输入中文',
                    },
                  ],
                })(
                  <Input style={{ width: '445px' }} placeholder="请输入" />
                )}
              </FormItem>
          }*/}





          <FormItem
            {...formItemLayout}
            label={formatMessage({ id: 'iot.permission.columns.permission_name' })}
            required={true}
          >
            {getFieldDecorator('permission_name', {
              initialValue: modalType == 'edit' ? this.props.updateData.permission_name : undefined,
              validateTrigger: ['onChange', 'onBlur'],
              rules: [
                {
                  pattern: /^[^ ]+$/,
                  max: 32,
                  required: true,
                  whitespace: true,
                  message: '请输入32位以内' + formatMessage({ id: 'iot.permission.columns.permission_name' })+ '(不能包含空格)',
                },

              ],
            })(
              <Input style={{ width: '445px' }} placeholder="请输入" />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label={formatMessage({ id: 'iot.permission.columns.is_left_menu' })}
            required={true}
          >
            {getFieldDecorator('is_left_menu', {
              initialValue: modalType == 'edit' ? this.props.updateData.is_left_menu : undefined,
              validateTrigger: ['onChange', 'onBlur'],
              rules: [
                {
                  required: true,
                  message: '请选择' + formatMessage({ id: 'iot.permission.columns.is_left_menu' }),
                },

              ],
            })(
              <Select placeholder="请选择" style={{ width: '445px' }} onChange={() => this.selectMenu()} >
                {typesList && typesList.length > 0 ?
                  typesList.map(function (item) {
                    return <Option key={item.k} id={item.k}
                                   value={item.k}>{item.v}
                    </Option>;
                  }) : []
                }
              </Select>
            )}

          </FormItem>

          <FormItem
            {...formItemLayout}
            label={'功能标识'}
            required={true}
          >
            {getFieldDecorator('route', {
              initialValue: modalType == 'edit' ? this.props.updateData.route : undefined,
              validateTrigger: ['onChange', 'onBlur'],
              rules: [
                {
                  validator:(rule,valuse,callback)=>{
                    const message = this.validator(rule,valuse)
                    if(message ){
                     callback("功能标识不能含/")
                    }else {
                      callback()
                    }
                  }
                },
                {
                  max: 255,
                  required: true,
                  whitespace: true,
                  message: '请填写255位以下' + formatMessage({ id: 'iot.permission.columns.route' }),
                },
                {
                  pattern: /^[^ ]+$/,
                  message: '(不能包含空格)',
                },
              ],
            })(
              <Input style={{ width: '445px' }} placeholder="请输入" />
            )}
          </FormItem>
            {
                usePlatform?
                    <FormItem
                        {...formItemLayout}
                        label={formatMessage({ id: 'iot.permission.columns.platform_type' })}

                    >
                        {getFieldDecorator('platform_type', {
                            initialValue: modalType == 'edit' ? platformType : undefined,
                            validateTrigger: ['onChange', 'onBlur'],

                        })(
                            <Select mode="multiple" placeholder="请选择" style={{ width: 200, marginTop: 4, marginLeft: 5, }}  onChange={(value,opt)=> this.platformTypeChange (value)} >
                                {platformtnameList && platformtnameList.length > 0 ?
                                    platformtnameList.map(function (item) {
                                        return <Option key={item.k} id={item.k}
                                                       value={item.k}>{item.v}
                                        </Option>;
                                    }) : []
                                }

                            </Select>
                        )}
                    </FormItem>
                    :
                    []
            }


          <FormItem
            {...formItemLayout}
            label="所属页面"
          >
            {getFieldDecorator('permission_pid', {
              validateTrigger: ['onChange', 'onBlur'],
              initialValue: modalType == 'edit' &&  this.props.updateData.permission_pid ? this.props.updateData.permission_pid : undefined,
              rules:  [

              ],
            })(

              <TreeSelect
                showSearch
                filterTreeNode={(inputValue,treeNode)=>{
                  if(treeNode.props.title.indexOf(inputValue) != -1){
                    return true;
                  }
                  return false
                }}
                style={{ width: '445px' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择"
                allowClear
                treeDefaultExpandAll
              >
                {noRouteTreeList && noRouteTreeList.length > 0 ?this.renderTreeNodes(noRouteTreeList) :[]}
              </TreeSelect>
            )}
          </FormItem>

        </div>


      </Modal>
    );
  }
}
